// pages/modifyRoom/modifyRoom.js
var common = require('../../utils/common.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    houseId:'',
    data: {},
    roomsConf: [],//房间配置
    listDatas: [],//房源数据
    houseindex: 0,//房源选择
    floorList: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],//楼层
    floorindex: 0,//楼层
    roomTypeList: [],//户型
    roomtypeindex: 0,//选择户型下标
    payTypeList: [],//付款方式列表
    paytypeindex: 0,//付款方式下标
    picList: [],//房间网络图片
    addpics: [],//用户新添加的图片 需要上传
    roomcode:'',//房号
    area: '',//面积
    price: '',//租金
    // picLength:"",
  },

  initData: function () {
    var that = this;
    //付款方式
    common._get('/wx/dict/list', { key: 'CHARGEMODE' },
      //成功
      function (res) {
        console.log(res.data)
        if (res.data.success) {
          that.setData({
            payTypeList: res.data.data,
          })
        }
      });
    //获取户型
    common._get('/wx/dict/list', { key: 'HUXING' },
      //成功
      function (res) {
        if (res.data.success) {
          that.setData({
            roomTypeList: res.data.data,
          })
        }
      });
    //获取数据
    common._get('/wx/house/detail', { houseId: this.data.houseId },
      //成功
      function (res) {
        console.log(res.data);
        if (res.data.success) {
          // that.setData({
          //   data: res.data.data,
          //   floorindex: res.data.data.floorName - 1,//楼层
          //   roomtypeindex: res.data.data.house_type - 1,//选择户型下标
          //   paytypeindex: res.data.data.chargemode - 1,//付款方式下标
          // })
          // //设置配置
          // that.setData({
          //   roomsConf: JSON.parse(res.data.data.furniture),
          //   picList: res.data.data.pics,
          // })
          //设置标题
          wx.setNavigationBarTitle({
            title: res.data.data.name,
          })

        }
      });
  },

  //点击添加房间配置
  addConfigClick: function () {
    if (this.data.roomsConf && this.data.roomsConf.length > 0) {
      wx.setStorageSync('conf', this.data.roomsConf)
    }
    wx.navigateTo({
      url: '../addConfig/addConfig',
    })
  },
  //点击删除房间配置
  deleteConfigClick: function (e) {
    var idx = e.target.dataset.index;
    console.log(idx)
    var conf = this.data.roomsConf;
    conf.splice(idx, 1)
    console.log(conf)
    this.setData({
      roomsConf: conf,
    })
  },
  //添加普通图片
  addimgClick: function () {
    var that = this;
    var count = 10 - (that.data.addpics.length + that.data.picList.length)
    wx.chooseImage({
      count: count, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempPicAdd = that.data.addpics.concat(res.tempFilePaths);
        if (tempPicAdd.length + that.data.picList.length > 10) {
          tempPicAdd.splice(10 - that.data.picList.length, tempPicAdd.length - (10 - that.data.picList.length));
        }
        that.setData({
          addpics: tempPicAdd,
        })
      }
    })
  },
  //预览图片
  ckimg: function (e) {
    var url = [];
    url.push(e.target.dataset.url);
    wx.previewImage({
      current: '', // 当前显示图片的http链接
      urls: url // 需要预览的图片http链接列表
    })
  },
  //删除图片
  deleteimg: function (e) {
    var that = this;
    var index = e.target.dataset.index;
    console.log(index)
    var i = index + 1;
    wx.showModal({
      title: '删除提示！',
      content: '确定要删除第' + i + '张图吗?',
      success: function (res) {
        //点击确认
        if (res.confirm) {

          common._get('/wx/room/pic/delete', { picId: that.data.data.pics[index].id },
            //成功
            function (res) {
              if (res.data.success) {
                var pics = that.data.picList
                pics.splice(index, 1);
                that.setData({
                  picList: pics
                })
              }
            });
          // 

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  //删除本地添加的图片
  deleteAddImg: function (e) {
    var that = this;
    var index = e.target.dataset.index;
    console.log(index);
    var i = index + 1 + that.data.picList.length;
    wx.showModal({
      title: '删除提示！',
      content: '确定要删除第' + i + '张图吗?',
      success: function (res) {
        //点击确认
        if (res.confirm) {
          var pics = that.data.addpics
          pics.splice(index, 1);
          that.setData({
            addpics: pics
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  //房名输入框
  roomcodeInput: function (e) {
    this.setData({
      roomcode: e.detail.value
    })
  },

  //面积输入框
  areaInput: function (e) {
    this.setData({
      area: e.detail.value
    })
  },
  //租金输入框
  priceInput: function (e) {
    this.setData({
      price: e.detail.value
    })
  },
  //备注输入框
  descriptionInput: function (e) {
    this.setData({
      description: e.detail.value
    })
  },
  //户型选择
  roomsTypeChabge: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    this.setData({
      roomtypeindex: e.detail.value,
    })
  },
  // 楼层选择
  floorChange: function (e) {
    this.setData({
      floorindex: e.detail.value,
    })

  },
  //付款方式选择
  payTypeChabge: function (e) {
    this.setData({
      paytypeindex: e.detail.value,
    })
  },


  //添加房间数据
  getAddRoomData: function () {
    var data = {
      // id: this.data.id,
      houseId: this.data.houseId,//房屋ID
      floorName: this.data.floorList[this.data.floorindex],//所在楼层
      roomcode: this.data.roomcode,//房号
      area: this.data.area ,//面积
      houseType: this.data.roomTypeList[this.data.roomtypeindex].key,//户型
      price: this.data.price,//租金
      chargemode: this.data.payTypeList[this.data.paytypeindex].key,//付款方式
      furniture: JSON.stringify(this.data.roomsConf),//房间配置
      description: this.data.description,//备注
    }
    return data;
  },
  //提交图片
  submitImg: function (id) {
    var that = this;
    var index = 0;//用于标记上传成功了多少张图片  目前暂未使用
    for (var i = 0; i < that.data.addpics.length; i++) {
      common._upload_file('/wx/room/savepic', that.data.addpics[i], 'files', { roomId: id },
        function (res) {
          console.log(res)
          if (res.success){
            wx.setStorageSync('modifyRoom', "success")
            wx.setStorageSync('result', 'result');
            //删除上传成功图片
            that.data.addpics.splice(index, 1);
            index++
            if (index < i) {
              wx.showToast({
                title: '第' + index + '张成功',
              })
            } else {//全部完成上传
              //删除全部图片
              that.data.addpics.splice(0, that.data.addpics.length);
              wx.showModal({
                title: '提示！',
                content: '全部图片上传成功',
                showCancel: false,
                success: function (res) {
                  //点击确认
                  wx.navigateBack();
                }
              })
            }
            //删除更新
            that.setData({
              addpics: that.data.addpics
            })
          }
        })
      // 
    }


  },
  //提交数据
  submit: function () {
    
    var that = this;
    if (this.data.roomcode==''){
        wx.showToast({
          title: '请输入房号',
          image: '../../image/shibai.png',
        });
        return;

    }
    if (this.data.area == '') {
      wx.showToast({
        title: '请输入面积',
        image: '../../image/shibai.png',
      });
      return;
    }
    if (this.data.price == '') {
      wx.showToast({
        title: '请输入租金',
        image: '../../image/shibai.png',
      });
      return;
    }
    //添加房间
    var datar = this.getAddRoomData();
    console.log(datar)
    common._get('/wx/room/save', datar,
      //成功
      function (res) {
        console.log('res.data')
        console.log(res.data)
        if (res.data.success) {
          if (that.data.addpics.length > 0) {
            that.submitImg(res.data.data.roomId);
          } else {
            wx.showModal({
              title: '提示！',
              content: '添加房间成功',
              showCancel: false,
              success: function (res) {
                //点击确认
                wx.setStorageSync('result', 'result');
                wx.setStorageSync('modifyRoom', "success")
              }
            })
          }

        }
      });

  },
  back:function(){
    wx.setStorageSync('result', 'result');
    wx.showToast({
      title: '添加房间成功',
    })
    //延时两秒关闭当前页面
    setTimeout(function () {
      wx.navigateBack();
    }, 2000)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.house_id)
    this.setData({
      houseId: options.house_id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.initData();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    //添加房间配置返回
    var addConfig = wx.getStorageSync('addconfig');
    wx.removeStorageSync('addconfig')
    if (addConfig.length > 0) {
      // addConfig = addConfig.concat(this.data.roomsConf)
      this.setData({
        roomsConf: addConfig,
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})